/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.dqhrm.service.impl;

import cn.hutool.core.util.ObjectUtil;
import me.zhengjie.config.FileProperties;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.dqhrm.domain.DqDoctors;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.dqhrm.util.Gender;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.dqhrm.repository.DqDoctorsRepository;
import me.zhengjie.modules.dqhrm.service.DqDoctorsService;
import me.zhengjie.modules.dqhrm.service.dto.DqDoctorsDto;
import me.zhengjie.modules.dqhrm.service.dto.DqDoctorsQueryCriteria;
import me.zhengjie.modules.dqhrm.service.mapstruct.DqDoctorsMapper;
import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;

import org.springframework.web.multipart.MultipartFile;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;
import java.io.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author Kuki Wu
* @date 2024-12-06
**/
@Service
@RequiredArgsConstructor
public class DqDoctorsServiceImpl implements DqDoctorsService {
    private final PasswordEncoder passwordEncoder;
    private final DqDoctorsRepository dqDoctorsRepository;
    private final DqDoctorsMapper dqDoctorsMapper;

    private final FileProperties properties;
    @Override
    public PageResult<DqDoctorsDto> queryAll(DqDoctorsQueryCriteria criteria, Pageable pageable){
        Page<DqDoctors> page = dqDoctorsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(dqDoctorsMapper::toDto));
    }

    @Override
    public List<DqDoctorsDto> queryAll(DqDoctorsQueryCriteria criteria){
        return dqDoctorsMapper.toDto(dqDoctorsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DqDoctorsDto findById(Long id) {
        DqDoctors dqDoctors = dqDoctorsRepository.findById(id).orElseGet(DqDoctors::new);
        ValidationUtil.isNull(dqDoctors.getId(),"DqDoctors","id",id);
        return dqDoctorsMapper.toDto(dqDoctors);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(DqDoctors resources) {
        if(dqDoctorsRepository.findByPhoneNumber(resources.getPhoneNumber()) != null){
            throw new EntityExistException(DqDoctors.class,"phone_number",resources.getPhoneNumber());
        }
        if(dqDoctorsRepository.findByIdCardNumber(resources.getIdCardNumber()) != null){
            throw new EntityExistException(DqDoctors.class,"id_card_number",resources.getIdCardNumber());
        }
        dqDoctorsRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DqDoctors resources) {
        DqDoctors dqDoctors = dqDoctorsRepository.findById(resources.getId()).orElseGet(DqDoctors::new);
        ValidationUtil.isNull( dqDoctors.getId(),"DqDoctors","id",resources.getId());
        /*dqDoctors = dqDoctorsRepository.findByPhoneNumber(resources.getPhoneNumber());
        if(dqDoctors != null && !dqDoctors.getId().equals(dqDoctors.getId())){
            throw new EntityExistException(DqDoctors.class,"phone_number",resources.getPhoneNumber());
        }
        dqDoctors = dqDoctorsRepository.findByIdCardNumber(resources.getIdCardNumber());
        if(dqDoctors != null && !dqDoctors.getId().equals(dqDoctors.getId())){
            throw new EntityExistException(DqDoctors.class,"id_card_number",resources.getIdCardNumber());
        }*/
        DqDoctors existingDoctor = findExistingDoctor(resources);
        if (existingDoctor == null) {
                String msg =  " 医生信息不存在！";
                throw new BadRequestException(msg);
        }
        dqDoctors.copy(resources);
        dqDoctorsRepository.save(dqDoctors);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> updateAvatar(MultipartFile multipartFile, Long doctorId) {
        // 文件大小验证
        FileUtil.checkSize(properties.getAvatarMaxSize(), multipartFile.getSize());
        // 验证文件上传的格式
        String image = "gif jpg png jpeg";
        String fileType = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        if(fileType != null && !image.contains(fileType)){
            throw new BadRequestException("文件格式错误！, 仅支持 " + image +" 格式");
        }
        DqDoctors dqDoctors = dqDoctorsRepository.findById(doctorId).orElseGet(DqDoctors::new);
        ValidationUtil.isNull( dqDoctors.getId(),"DqDoctors","id", doctorId);

        String oldPath = dqDoctors.getAvatarPath();
        File file = FileUtil.upload(multipartFile, properties.getPath().getAvatar());
        dqDoctors.setAvatarPath(Objects.requireNonNull(file).getPath());
        dqDoctors.setAvatarName(file.getName());
        dqDoctorsRepository.save(dqDoctors);
        if (StringUtils.isNotBlank(oldPath)) {
            FileUtil.del(oldPath);
        }
        //@NotBlank String username = dqDoctors.getUsername();
        //flushCache(username);
        return new HashMap<String, String>(1) {{
            put("avatar", file.getName());
        }};
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmail(Long doctorId, String email) {
        dqDoctorsRepository.updateEmail(doctorId, email);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePass(Long doctorId, String pass) {
        dqDoctorsRepository.updatePass(doctorId, pass);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPwd(Set<Long> ids, String pwd) {
        dqDoctorsRepository.resetPwd(ids, pwd);
    }
    @Override
    public void deleteAll(Set<Long> ids) {
        dqDoctorsRepository.deleteAllByIdIn(ids);
    }

    @Override
    public void download(List<DqDoctorsDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DqDoctorsDto dqDoctors : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("姓名", dqDoctors.getRealName());
            map.put("昵称", dqDoctors.getNickName());
            map.put("微信名", dqDoctors.getWxName());
            map.put("微信号", dqDoctors.getWxNo());
            map.put("微信OpenID号", dqDoctors.getWxOpenid());
            map.put("电话号码", dqDoctors.getPhoneNumber());
            map.put("身份证号", dqDoctors.getIdCardNumber());
            map.put("本平台登录密码", dqDoctors.getDqHrmPassword());
            map.put("出生年月日", dqDoctors.getBirthDate());
            map.put("性别", dqDoctors.getGender());
            map.put("民族", dqDoctors.getEthnicity());
            map.put("身份证省份", dqDoctors.getIdCardProvince());
            map.put("身份证地址", dqDoctors.getIdCardAddress());
            map.put("电子邮箱", dqDoctors.getEmail());
            map.put("医师职称", dqDoctors.getPhysicianTitle());
            map.put("注册科室", dqDoctors.getRegisteredDepartment());
            map.put("医师职称注册范围", dqDoctors.getTitleRegistrationScope());
            map.put("医师职证称编号", dqDoctors.getTitleCertificateNumber());
            map.put("医师证执业证获取时间", dqDoctors.getPracticeCertificateObtainedDate());
            map.put("医师证原注册单位省份", dqDoctors.getOriginalRegistrationProvince());
            map.put("原注册单位城市", dqDoctors.getOriginalRegistrationCity());
            map.put("医师证原注册单位名称", dqDoctors.getOriginalRegistrationUnitName());
            map.put("医师证原注册单位级别", dqDoctors.getOriginalRegistrationUnitLevel());
            map.put("医师证医院性质", dqDoctors.getHospitalNature());
            map.put("医师资格证编号", dqDoctors.getQualificationCertificateNumber());
            map.put("资格证获取时间", dqDoctors.getQualificationObtainedDate());
            map.put("专业类别", dqDoctors.getSpecialtyCategory());
            map.put("毕业学校", dqDoctors.getGraduationSchool());
            map.put("学历", dqDoctors.getEducationLevel());
            map.put("医师执业证编号", dqDoctors.getPhysicianLicenseNumber());
            map.put("药师专业类别", dqDoctors.getPharmacistSpecialtyCategory());
            map.put("药师咨格证编号", dqDoctors.getPharmacistQualificationCertificateNumber());
            map.put("药师管理号", dqDoctors.getPharmacistManagementNumber());
            map.put("药师注册证编号", dqDoctors.getPharmacistRegistrationCertificateNumber());
            map.put("药师证签发单位", dqDoctors.getPharmacistIssuingUnit());
            map.put("药师执业类别", dqDoctors.getPharmacistPracticeCategory());
            map.put("药师执业范围", dqDoctors.getPharmacistPracticeScope());
            map.put("药师注册地址", dqDoctors.getPharmacistRegistrationAddress());
            map.put("个人简介", dqDoctors.getPersonalProfile());
            map.put("擅长科室及疾病用药", dqDoctors.getSpecialtiesAndDiseases());
            map.put("其他医疗相关证件", dqDoctors.getOtherMedicalCertificates());
            map.put("开户行", dqDoctors.getBankName());
            map.put("银行卡帐号", dqDoctors.getBankAccountNumber());
            map.put("总收入", dqDoctors.getTotalRevenue());
            map.put("等级评价", dqDoctors.getGrade());
//            map.put("是否激活", dqDoctors.getIsEnable());
//            map.put("审核状态", dqDoctors.getAuditStatus());
//            map.put("审核结果信息", dqDoctors.getAuditResult());
            map.put("审核时间", dqDoctors.getAuditTime());
            map.put("注册时间", dqDoctors.getRegistrationTime());
/*            map.put("录入时间", dqDoctors.getCreateTime());
            map.put("录入人员", dqDoctors.getCreateUserId());
            map.put("修改时间", dqDoctors.getModifyTime());
            map.put("修改人员", dqDoctors.getModifyUserId());
            map.put("最后登录时间", dqDoctors.getLastLonginTime());*/
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public void importDoctors(MultipartFile file, Long userId) throws IOException, ParseException {
        String fileName = file.getOriginalFilename();
        if (fileName.endsWith(".csv") || fileName.endsWith(".txt")) {
            parseCsvOrTxt(file, userId);
        } else if (fileName.endsWith(".xlsx")) {
            parseExcel(file, userId);
        } else {
            throw new IllegalArgumentException("Unsupported file type");
        }
    }

    private void parseCsvOrTxt(MultipartFile file, Long userId) throws IOException, ParseException {
        List<DqDoctors> doctors = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8));
             CSVParser csvParser = new CSVParser(br, CSVFormat.DEFAULT.withFirstRecordAsHeader())) {
            for (CSVRecord csvRecord : csvParser) {
                DqDoctors doctor = mapToDoctor(csvRecord, userId);
                 //DqDoctors doctor = findExistingDoctor(mapToDoctor(csvRecord));
                 if (doctor != null) {
                    doctors.add(doctor);
                }
            }
        }
        if (doctors.isEmpty()){ return;}
        dqDoctorsRepository.saveAll(doctors);
    }

    private void parseExcel(MultipartFile file, Long userId) throws IOException, ParseException {
        List<DqDoctors> doctors = new ArrayList<>();
        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rows = sheet.iterator();
            int rowNumber = 0;
            while (rows.hasNext()) {
                Row currentRow = rows.next();
                if (rowNumber == 0) {
                    rowNumber++;
                    continue; // Skip header
                }
                Iterator<Cell> cellsInRow = currentRow.iterator();
                DqDoctors doctor = mapToDoctor(cellsInRow, userId);
                //DqDoctors doctor = findExistingDoctor(mapToDoctor(cellsInRow));
                if (doctor != null) {
                    doctors.add(doctor);
                    rowNumber++;
                }
            }
        }

        if (doctors.isEmpty()){ return;}

        dqDoctorsRepository.saveAll(doctors);
    }

    private DqDoctors mapToDoctor(CSVRecord record, Long userId) throws ParseException {
        DqDoctors doctor = new DqDoctors();
        doctor.setRealName(record.get("姓名"));
        doctor.setNickName("");
        doctor.setWxName("");
        doctor.setWxNo("");
        doctor.setWxOpenid("");
        doctor.setPhoneNumber(record.get("电话号码"));
        doctor.setIdCardNumber(record.get("'身份证号"));
        doctor.setDqHrmPassword(passwordEncoder.encode("123456"));
        doctor.setBirthDate(parseDate(record.get("出生年月日")));
        // doctor.setGender(record.get("性别"));
        if (record.get("性别").equals("男")) {
            doctor.setGender("1");
            doctor.setAvatarName("doctor_avatar_m.png");
            doctor.setAvatarPath("@/assets/images/doctor_avatar_m.png");
        } else {
            doctor.setGender("0");
            doctor.setAvatarName("doctor_avatar_f.png");
            doctor.setAvatarPath("@/assets/images/doctor_avatar_f.png");
        }

        doctor.setEthnicity(record.get("民族"));
        doctor.setIdCardProvince(record.get("身份证省份"));
        doctor.setIdCardAddress(record.get("身份证地址"));
        doctor.setEmail(record.get("电子邮箱"));
        doctor.setPhysicianTitle(record.get("医师职称"));
        doctor.setRegisteredDepartment(record.get("注册科室"));
        doctor.setTitleRegistrationScope(record.get("医师职称注册范围"));
        doctor.setTitleCertificateNumber(record.get("医师职证称编号"));
        doctor.setPracticeCertificateObtainedDate(parseDate(record.get("医师证执业证获取时间")));
        doctor.setOriginalRegistrationProvince(record.get("医师证原注册单位省份"));
        doctor.setOriginalRegistrationCity(record.get("原注册单位城市"));
        doctor.setOriginalRegistrationUnitName(record.get("医师证原注册单位名称"));
        doctor.setOriginalRegistrationUnitLevel(record.get("医师证原注册单位级别"));
        doctor.setHospitalNature(record.get("医师证医院性质"));
        doctor.setQualificationCertificateNumber(record.get("医师资格证编号"));
        doctor.setQualificationObtainedDate(parseDate(record.get("资格证获取时间")));
        doctor.setSpecialtyCategory(record.get("专业类别"));
        doctor.setGraduationSchool(record.get("毕业学校"));
        doctor.setEducationLevel(record.get("'学历"));
        doctor.setPhysicianLicenseNumber(record.get("医师执业证编号"));
        doctor.setPharmacistSpecialtyCategory(record.get("药师专业类别"));
        doctor.setPharmacistQualificationCertificateNumber(record.get("药师咨格证编号"));
        doctor.setPharmacistManagementNumber(record.get("药师管理号"));
        doctor.setPharmacistRegistrationCertificateNumber(record.get("药师注册证编号"));
        doctor.setPharmacistIssuingUnit(record.get("药师证签发单位"));
        doctor.setPharmacistPracticeCategory(record.get("药师执业类别"));
        doctor.setPharmacistPracticeScope(record.get("药师执业范围"));
        doctor.setPharmacistRegistrationAddress(record.get("药师注册地址'"));
        doctor.setPersonalProfile(record.get("个人简介"));
        doctor.setSpecialtiesAndDiseases(record.get("擅长科室及疾病用药"));
        doctor.setOtherMedicalCertificates(record.get("其他医疗相关证件"));
        doctor.setBankName(record.get("开户行"));
        doctor.setBankAccountNumber(record.get("银行卡帐号"));
        doctor.setTotalRevenue(new BigDecimal("0"));
        doctor.setGrade("");
        doctor.setIsEnable(false);
        doctor.setAuditStatus(0);
        doctor.setAuditResult("");
        doctor.setAuditTime(null);
        doctor.setLastLonginTime(null);
        return doctor;
    }

    private DqDoctors mapToDoctor(Iterator<Cell> cells, Long userId) throws ParseException {
        DqDoctors doctor = new DqDoctors();
        doctor.setRealName(getCellValue(cells.next()));
        doctor.setNickName("");
        doctor.setWxName("");
        doctor.setWxNo("");
        doctor.setWxOpenid("");
        doctor.setPhoneNumber(getCellValue(cells.next()));
        doctor.setIdCardNumber(getCellValue(cells.next()));
        doctor.setDqHrmPassword(passwordEncoder.encode("123456"));
        doctor.setBirthDate(parseDate(getCellValue(cells.next())));
        // doctor.setGender(getCellValue(cells.next()));
        if (getCellValue(cells.next()).equals("男")) {
            doctor.setGender("1");
            doctor.setAvatarName("doctor_avatar_m.png");
            doctor.setAvatarPath("@/assets/images/doctor_avatar_m.png");
        } else {
            doctor.setGender("0");
            doctor.setAvatarName("doctor_avatar_f.png");
            doctor.setAvatarPath("@/assets/images/doctor_avatar_f.png");
        }
        doctor.setEthnicity(getCellValue(cells.next()));
        doctor.setIdCardProvince(getCellValue(cells.next()));
        doctor.setIdCardAddress(getCellValue(cells.next()));
        doctor.setEmail(getCellValue(cells.next()));
        doctor.setPhysicianTitle(getCellValue(cells.next()));
        doctor.setRegisteredDepartment(getCellValue(cells.next()));
        doctor.setTitleRegistrationScope(getCellValue(cells.next()));
        doctor.setTitleCertificateNumber(getCellValue(cells.next()));
        doctor.setPracticeCertificateObtainedDate(parseDate(getCellValue(cells.next())));
        doctor.setOriginalRegistrationProvince(getCellValue(cells.next()));
        doctor.setOriginalRegistrationCity(getCellValue(cells.next()));
        doctor.setOriginalRegistrationUnitName(getCellValue(cells.next()));
        doctor.setOriginalRegistrationUnitLevel(getCellValue(cells.next()));
        doctor.setHospitalNature(getCellValue(cells.next()));
        doctor.setQualificationCertificateNumber(getCellValue(cells.next()));
        doctor.setQualificationObtainedDate(parseDate(getCellValue(cells.next())));
        doctor.setSpecialtyCategory(getCellValue(cells.next()));
        doctor.setGraduationSchool(getCellValue(cells.next()));
        doctor.setEducationLevel(getCellValue(cells.next()));
        doctor.setPhysicianLicenseNumber(getCellValue(cells.next()));
        doctor.setPharmacistSpecialtyCategory(getCellValue(cells.next()));
        doctor.setPharmacistQualificationCertificateNumber(getCellValue(cells.next()));
        doctor.setPharmacistManagementNumber(getCellValue(cells.next()));
        doctor.setPharmacistRegistrationCertificateNumber(getCellValue(cells.next()));
        doctor.setPharmacistIssuingUnit(getCellValue(cells.next()));
        doctor.setPharmacistPracticeCategory(getCellValue(cells.next()));
        doctor.setPharmacistPracticeScope(getCellValue(cells.next()));
        doctor.setPharmacistRegistrationAddress(getCellValue(cells.next()));
        doctor.setPersonalProfile(getCellValue(cells.next()));
        doctor.setSpecialtiesAndDiseases(getCellValue(cells.next()));
        doctor.setOtherMedicalCertificates(getCellValue(cells.next()));
        doctor.setBankName(getCellValue(cells.next()));
        doctor.setBankAccountNumber(getCellValue(cells.next()));
        doctor.setTotalRevenue(new BigDecimal("0"));
        doctor.setGrade("");
        doctor.setIsEnable(false);
        doctor.setAuditStatus(0);
        doctor.setAuditResult("");
        doctor.setAuditTime(null);
        doctor.setRegistrationTime(new Timestamp(new Date().getTime()));
        doctor.setLastLonginTime(null);
        return doctor;
    }

    private String getCellValue(Cell cell) {
        Object value = "";
        if (cell!=null){
            try {
                switch (cell.getCellType()) {
                    case STRING:
                        //return cell.getStringCellValue();
                        value = cell.getStringCellValue();
                        break;
                    case NUMERIC:
                        if (DateUtil.isCellDateFormatted(cell)) {
                            Date date = cell.getDateCellValue();
                            if (date != null) {
                                // 标准0点 1970/01/01 08:00:00
                                if (date.getTime() % 86400000 == 16 * 3600 * 1000 && cell.getCellStyle().getDataFormat() == 14) {
                                    value = new SimpleDateFormat("yyyy-MM-dd").format(date);
                                } else {
                                    value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
                                }
                                //return cell.getDateCellValue().toString();
                            }
                        } else {
                            //return String.valueOf(cell.getNumericCellValue());

                            //System.out.println("Value:"+cell.getNumericCellValue());

                            String numberStr = new HSSFDataFormatter().formatCellValue(cell);
                            // 货币格式，如：1,200.00
                            if (numberStr.contains(",")) {
                                numberStr = numberStr.replace(",", "");
                            }
                            if (numberStr.contains("E")) {    // 科学计算法
                                numberStr = new DecimalFormat("0").format(cell.getNumericCellValue());    //4.89481368464913E14还原为长整数
                                value = Long.parseLong(numberStr);
                            } else {
                                if (numberStr.contains(".")) {    // 小数
                                    value = Double.parseDouble(numberStr);
                                } else {    // 转换为整数
                                    value = Long.parseLong(numberStr);
                                }
                            }
                        }
                        break;
                    case BOOLEAN:
                        //return String.valueOf(cell.getBooleanCellValue());
                        value = (cell.getBooleanCellValue()==true?"Y":"M");
                        break;
                    case FORMULA:
                        value =  cell.getCellFormula();
                        break;
                    default:
                        return "";
                }
            }catch (Exception e){
                System.out.println("Error parsing cell value: " + cell.getCellType());
                e.printStackTrace();
                value= "";
            }
        }
        return value.toString();
    }

    private Timestamp parseDate(String dateStr) throws ParseException {
        if (dateStr == null || dateStr.isEmpty()) {
            return null;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return new Timestamp(dateFormat.parse(dateStr).getTime());
    }

    private Timestamp parseDateTime(String dateTimeStr) throws ParseException {
        if (dateTimeStr == null || dateTimeStr.isEmpty()) {
            return null;
        }
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return new Timestamp(dateTimeFormat.parse(dateTimeStr).getTime());
    }


    private DqDoctors findExistingDoctor(DqDoctors doctor) {
        Optional<DqDoctors> byPhoneNumber = dqDoctorsRepository.findByPhoneNumber(doctor.getPhoneNumber());
        if (byPhoneNumber.isPresent()) {
            return byPhoneNumber.get();
        }
        Optional<DqDoctors> byIdCardNumber = dqDoctorsRepository.findByIdCardNumber(doctor.getIdCardNumber());
        if (byIdCardNumber.isPresent()) {
            return byIdCardNumber.get();
        }
        Optional<DqDoctors> byEmail = dqDoctorsRepository.findByEmail(doctor.getEmail());
        if (byEmail.isPresent()) {
            return byEmail.get();
        }
        return null;
    }
}